package com.tgy.utils;

/***
 * @ClassName: Sendmail
 * @Description:
 * @Auther: 送一一块二向箔
 * @Date: 17:13 2021/12/13
 * @version : V1.0
 */
import com.tgy.entity.User;
import com.sun.mail.util.MailSSLSocketFactory;
import com.tgy.MailDamo01;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.*;
import java.util.Properties;

//网站3秒原则::用户体验
//多线程实现用户体验! (异步处理)
public class Sendmail extends Thread {
    static  Properties prop;
    static {
        prop=new Properties();
        InputStream resourceAsStream = MailDamo01.class.getClassLoader().getResourceAsStream("mail.properties");
        try {
            prop.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private User user;

    public Sendmail(User user) throws FileNotFoundException {
        this.user=user;
    }

    //重写run方法的实现，在run 方法中发送邮件给指定的用户
    @Override
    public void run() {
        try {

            //川于给用户发送邮件的邮箱
            String from = prop.getProperty("mail.url");
            //邮箱的密码
            String password = prop.getProperty("mail.password");
            //发送邮件的服务器地址
            String host = prop.getProperty("mail.host") ;

            //QQ邮箱需要设置SSL加密
            MailSSLSocketFactory sf=new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            prop.put("mail.smtp.ssl.socketFactory",sf);

            //使用javaMail发送邮件的5个步骤
            //1.创建定义整个应用程序所需要的环境信息的session对象
            Session session= Session.getDefaultInstance(prop, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(from,password);
                }
            });
            //开启session的debug模式，这样可以查看到程序发送Email的运行状态
            session.setDebug(true);
            //2.通过session得到transport对象
            Transport ts=session.getTransport();
            //3.使用邮箱的用户名和授权码连上邮件服务器
            ts.connect(host,from,password);
            //4.创建邮件：写文件
            //注意需要传递session
            MimeMessage message=new MimeMessage(session);
            //指明邮件的发件人
            message.setFrom(new InternetAddress(from));
            //指明邮件的收件人
            message.setRecipient(Message.RecipientType.TO,new InternetAddress(user.getEmail()));
            //邮件标题
            message.setSubject("注册通知");
            //邮件的文本内容
            message.setContent("恭喜你("+user.getUsername()+")成功注册！"+"密码："+user.getPassword(),"text/html;charset=UTF-8");
            //5.发送邮件
            ts.sendMessage(message,message.getAllRecipients());

            //6.关闭连接
            ts.close();
        }catch (Exception e){
            System.out.println(e);
        }

    }
}
